﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using Century.Common.Business.BOL.Common;
using Century.Common.Business.BOL.Core;
using Century.Models.Core;
using Ionic.Zip;
using Century.Web.Security.Attributes;
using Century.Web.UI.MVC;

namespace Century.CMS.Areas.Admin.Controllers
{
    // [Kooboo.CMS.Web.Authorizations.Authorization(AreaName = "AdminTools", Group = "", Name = "ImportEmailTemplate")]
    [Authorization(Group = "", Name = "ImportEmailTemplate")]
    public class ImportEmailTemplateController : CenturyAdminBaseController
    {
        //
        // GET: /AdminTools/ImportEmailTemplate/

        public ActionResult Index()
        {
            var selectedProject = Request.Params["ddlFsaNonFSA"] ?? "FSA";
            List<string> projectType = new List<string>();
            projectType.Add("FSA");
            projectType.Add("NonFSA");
            ViewBag.ProjectType = new SelectList(projectType, selectedProject);
            ViewBag.ApplicationType = selectedProject;
           
            return View();
        }

        public ActionResult UploadTemplate()
        {
            var selectedProject = Request.Params["ddlFsaNonFSA"];

            Dictionary<string, int> images = new Dictionary<string, int>();
            Dictionary<string, int> docs = new Dictionary<string, int>();
            Dictionary<string, byte[]> htmls = new Dictionary<string, byte[]>();

            using (var zip = ZipFile.Read(Request.Files[0].InputStream))
            {

                foreach (var entry in zip.Entries)
                {
                    if (!entry.IsDirectory)
                    {
                        var reader = entry.OpenReader();
                        byte[] buffer = new byte[reader.Length];
                        int i = reader.Read(buffer, 0, Convert.ToInt32(reader.Length));
                        if (i > 0)
                        {
                            if (entry.FileName.ToLower().EndsWith(".html") || entry.FileName.ToLower().EndsWith(".htm"))
                            {
                                htmls.Add(Path.GetFileNameWithoutExtension(entry.FileName), buffer);
                            }
                            if (entry.FileName.ToLower().EndsWith(".gif") || entry.FileName.ToLower().EndsWith(".jpg") || entry.FileName.ToLower().EndsWith(".png"))
                            {
                                EmailFileType emailFile = null;
                                using (EmailFileTypeBSO emailFileTypeBSO = GetBSO<EmailFileTypeBSO>(selectedProject))
                                {
                                    emailFile = new EmailFileType()
                                     {
                                         Name = Path.GetFileName(entry.FileName),
                                         Content = buffer,
                                         MediaType = "image/" + Path.GetExtension(entry.FileName).Replace(".","")
                                     };
                                    emailFileTypeBSO.Insert(emailFile);
                                }
                                //buffer
                                images.Add(Path.GetFileName(entry.FileName), emailFile.Id);
                            }
                            else if (entry.FileName.ToLower().EndsWith(".doc") || entry.FileName.ToLower().EndsWith(".docx"))
                            {
                                using (EmailFileTypeBSO emailFileTypeBSO = GetBSO<EmailFileTypeBSO>(selectedProject))
                                {
                                    EmailFileType emailFile = new EmailFileType
                                    {
                                        Name = Path.GetFileName(entry.FileName),
                                        Content = buffer,
                                        MediaType = "application/vnd.ms-word.document.12"
                                    };
                                    emailFileTypeBSO.Insert(emailFile);
                                    docs.Add(Path.GetFileName(entry.FileName), emailFile.Id);
                                }
                                

                            }
                        }

                    }
                }
                ParsAndSaveTemplates(htmls, images, docs);
            }
            ViewBag.InsertedHTMLs = htmls.Select(c => c.Key).ToList();
            return View();
        }



        private void ParsAndSaveTemplates(Dictionary<string, byte[]> htmls, Dictionary<string, int> images, Dictionary<string, int> docs)
        {
            string selectedProject = Request.Params["ddlFsaNonFSA"];
            int selectedCountrySite = int.Parse(Request.Params["ddlCountrySite"]);
            foreach (var item in htmls)
            {
                string body = Encoding.UTF8.GetString(item.Value);
                Regex imageSrcExc = new Regex(@"(?<=<img\s+[^>]*?src=(?<q>['""]))(?<url>.+?)(?=\k<q>)");
                MatchCollection matches = imageSrcExc.Matches(body.ToLower());
                List<int> imageIds = new List<int>();
                foreach (Match match in matches)
                {
                    string fileName = Path.GetFileName(match.Value);
                    if (match.Value.ToLower().StartsWith("cid:"))
                    {
                        int id = 0;
                        int.TryParse(match.Value.Split(':')[1], out id);
                        if (id!= 0)
                        {
                            imageIds.Add(id);
                            continue;
                        }
                    }
                    int image = 0;
                    if (images.Count(c => c.Key.ToLower() == fileName.ToLower()) > 0)
                    {
                        image = images.First(c => c.Key.ToLower() == fileName.ToLower()).Value;
                    }
                    
                    body = body.Replace(match.Value, "cid:" + image);
                    if (!imageIds.Contains(image))
                    {
                        imageIds.Add(image);
                    }
                }
                using (EmailTemplateBSO emailTemplateBSO = GetBSO<EmailTemplateBSO>(selectedProject))
                {
                    EmailTemplate tmp = emailTemplateBSO.Find(c => c.Version, true, c => c.Name == item.Key && c.CountrySiteId == selectedCountrySite);
                    int version = tmp == null ? 1 : tmp.Version + 1;
                    string subject = tmp == null ? item.Key : tmp.Subject;

                    EmailTemplate eTemplate = new EmailTemplate()
                    {
                        Body = body,
                        EmailFileTypes = new List<EmailFileType>(),
                        CountrySiteId = selectedCountrySite,
                        Name = item.Key,
                        Version = version,
                        Subject = subject
                    };

                    foreach (int imageid in imageIds)
                    {
                        if (!eTemplate.EmailFileTypes.Any(c => c.Id == imageid))
                        {
                            eTemplate.EmailFileTypes.Add(emailTemplateBSO.GetEmailFileById(imageid));
                        }
                    }
                    foreach (KeyValuePair<string, int> doc in docs)
                    {
                        if (!eTemplate.EmailFileTypes.Any(c => c.Id == doc.Value))
                        {
                            eTemplate.EmailFileTypes.Add(emailTemplateBSO.GetEmailFileById(doc.Value));
                        }

                    }

                    emailTemplateBSO.Insert(eTemplate);
                }
            }


        }



    }
}
